<template>
  <div class="search-container">
    <!-- 顶部搜索栏 -->
    <div class="search-header">
      <van-icon name="arrow-left" class="back-icon" @click="onBack" />
      <div class="search-input-wrapper">
        <van-search
            v-model="searchValue"
            placeholder="按标题、标签 简单搜索"
            shape="round"
            background="transparent"
            :clearable="true"
        >
          <template #right-icon>
            <van-button
                type="primary"
                size="small"
                round
                class="search-btn"
                @click="onSearch"
            >搜索</van-button>
          </template>
        </van-search>
      </div>
    </div>

    <!-- 搜索记录 -->
    <div class="search-history" v-if="!searchValue">
      <div class="section-header">
        <span>搜索记录</span>
        <van-icon name="delete" @click="clearHistory" />
      </div>
      <div class="history-tags">
        <span class="tag" v-for="tag in historyTags" :key="tag" @click="toSearch(tag)">{{ tag }}</span>
      </div>
    </div>

    <!-- 热门作者 -->
    <div class="hot-authors" v-if="!searchValue">
      <div class="section-header">
        <span>热门作者</span>
      </div>
      <div class="author-list">
        <div class="author-item" v-for="author in hotAuthors" :key="author.id">
          <img :src="author.avatar" :alt="author.name" class="author-avatar">
          <span class="author-name">{{ author.name }}</span>
        </div>
      </div>
    </div>

    <!-- 热搜排行 -->
    <div class="hot-search" v-if="!searchValue">
      <div class="section-header">
        <span>热搜排行</span>
        <span class="hot-label">HOT</span>
      </div>
      <div class="hot-list">
        <div class="hot-item" v-for="(item, index) in hotSearchList" :key="index" @click="toNovelDetails(item.pid)">
          <span class="rank-number" :class="{'top-three': index < 3}">{{ index + 1 }}</span>
          <span class="book-name">{{ item.name }}</span>
          <span class="read-count">评分 {{ item.readCount }}</span>
        </div>
      </div>
    </div>

    <div v-if="showMessage">
      <span style="color: #666666;font-size: 14px;">很抱歉，没有找到相关的书籍!</span>
    </div>
    <!-- 搜索结果 -->
    <div class="search-results" v-if="searchValue && novelList.length">
      <div class="result-item" v-for="novel in novelList" :key="novel.name" @click="toNovelDetails(novel.id)">
        <img :src="novel.url" :alt="novel.name" class="result-image" />
        <div class="result-info">
          <h3 class="result-title">{{ novel.name }}</h3>
          <p class="result-description">{{ novel.description }}</p>
          <span class="result-people">简介: {{handleNovelSummary(novel.introduction)}}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import {Dialog} from "vant";

export default {
  name: 'SearchView',
  data() {
    return {
      searchValue: '',
      historyTags: [],
      hotAuthors: [
        { id: 1, name: 'Renter', avatar: 'https://via.placeholder.com/60' },
        { id: 2, name: 'Anna', avatar: 'https://via.placeholder.com/60' },
        { id: 3, name: 'Lita', avatar: 'https://via.placeholder.com/60' },
        { id: 4, name: 'Wetest', avatar: 'https://via.placeholder.com/60' }
      ],
      hotSearchList: [
        { name: '风起龙城', readCount: '98865' },
        { name: '佛系医妃有空间', readCount: '86523' },
        { name: '近战狂兵', readCount: '60005' },
        { name: '我的明朝之旅', readCount: '55698' },
        { name: '百炼飞升录', readCount: '50236' },
        { name: '女总裁的全能兵王', readCount: '9865' }
      ],
      user:{
        userId:1,
      },
      form:{},
      novelList:[],
      summaryLimit:40,
      showMessage:false,
      one:{},
    }
  },
  methods: {
    handleNovelSummary(introduction) {
      if (introduction.length > this.summaryLimit) {
        return introduction.slice(0, this.summaryLimit) + "...";
      }
      return introduction;
    },
    toSearch(tag){
      this.searchValue = tag;
      this.onSearch();
    },
    toNovelDetails(pid){
      this.$router.push({path: '/noveldetails',query: {id:pid}})
    },
    findRankingNovel(){
      axios.get("http://localhost:9999/api-novel/novel/findRankingNovel").then(res=>{
        this.hotSearchList=res.data
      })
    },
    findAuthor(){
      axios.get("http://localhost:9999/api-novel/author/findHotAuthor").then(res=>{
        this.hotAuthors=res.data
      })
    },
    findHistory(){
      axios.post("http://localhost:9999/api-novel/history/findHistoryContent?userId="+this.one.id).then(res=>{
        this.historyTags=res.data
      })
    },
    onBack() {
      this.$router.go(-1)
    },
    onSearch() {
      if (this.one==null){
        this.$toast("您还未登录")
      }else{
        this.form.keyword = this.searchValue
        this.form.userId = this.one.id
        axios.post("http://localhost:9999/api-novel/novel/findOneNovel", this.form).then(res => {
          if (res.data==''){
            this.showMessage=true;
          }else{
            this.novelList = res.data;
            this.findHistory();
          }
        })
      }
    },
    clearHistory() {
      Dialog.confirm({
        title: '删除历史记录',
        message: '你确定要删除所有历史记录吗？',
      })
          .then(() => {
            // on confirm
            axios.post("http://localhost:9999/api-novel/history/deleteAllHistory?userId=" + this.user.userId).then(res => {
              this.$toast.success('删除成功');
              this.findHistory()
            })
          })
          .catch(() => {
            // on cancel
          });
    }
  },
  created() {
    this.one = JSON.parse(localStorage.getItem("user"))
    if (this.one == null){
      this.$toast("您还未登录")
    }else{
      this.findHistory();
    }
    this.findAuthor();
    this.findRankingNovel();

  }
}
</script>

<style scoped>
.search-container {
  min-height: 100vh;
  background: #fff;
  padding: 16px;
}

.search-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 20px;
}

.back-icon {
  font-size: 20px;
}

.search-input-wrapper {
  flex: 1;
}

:deep(.van-search) {
  padding: 0;
}

:deep(.van-search__content) {
  background: #f5f5f5;
}

.search-btn {
  height: 32px;
  padding: 0 16px;
  margin-left: 8px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 500;
}

.history-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 24px;
}

.tag {
  padding: 6px 12px;
  background: #f5f5f5;
  border-radius: 16px;
  font-size: 14px;
  color: #333;
}

.author-list {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 24px;
}

.author-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.author-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  object-fit: cover;
}

.author-name {
  font-size: 14px;
  color: #333;
}

.hot-label {
  color: #ff4d4f;
  font-size: 14px;
  font-weight: bold;
}

.hot-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.hot-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.rank-number {
  width: 20px;
  color: #999;
  font-weight: 500;
}

.rank-number.top-three {
  color: #ff4d4f;
}

.book-name {
  flex: 1;
  font-size: 14px;
}

.read-count {
  color: #999;
  font-size: 12px;
}

.search-results {
  margin-top: 20px;
}

.result-item {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.result-image {
  width: 60px;
  height: 90px;
  border-radius: 4px;
  object-fit: cover;
  margin-right: 12px;
}

.result-info {
  flex: 1;
}

.result-title {
  font-size: 16px;
  font-weight: bold;
}

.result-description {
  font-size: 14px;
  color: #666;
}

.result-people {
  font-size: 12px;
  color: #999;
}
</style>
